package com.weixin.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/*")
public class LoginFilter implements Filter{

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) resp;
		//获得访问路径
		String uri = request.getRequestURI();
		//访问除了login.jsp和loginservlet 的jsp 和servlet 都需要验证
		if ( (uri.contains("jsp")&&!uri.endsWith("login.jsp")) || (uri.contains("UserServlet")&&!uri.endsWith("UserServlet/login"))||uri.endsWith(request.getContextPath()+"/")) {
			//需要验证登陆状态的路径
			HttpSession session = request.getSession();
			
			if(session.getAttribute("user")!=null) {
				//已登陆的 直接放行
				chain.doFilter(request, response);
				
			}else {
				//未登录  转发到login.jsp
				request.setAttribute("error", "请先登录！！");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
		} else {
			//直接放行的路径
			chain.doFilter(request, response);
		}
	}

}